
$(function() {
    //load icon
    $('body').hide().show();
    CKEDITOR.replace('editor1');
    //CKEDITOR.instances.editor1.insertHtml( '<p>This is a new paragraph.</p>' );
    var insertImage = function(){
        $(".btn-insert-image").on("click",function(){
            var val = $(this).siblings(".file-name").val();
            CKEDITOR.instances.editor1.insertHtml( '<a href="#">'+val+'</a>' );
        });
    }
    var sortFunction = function(){
        $(".sortable").sortable();
    }
    sortFunction();
    /* jquery upload */
    var settings = {
        url: "upload.php",
        dragDrop:true,
        fileName: "myfile",
        allowedTypes:"jpg,png,gif,doc,pdf,zip",
        returnType:"json",
        showFileCounter:false,
        showProgress:false,
        showDone:false,
        onSuccess:function(files,data,xhr)
        {
            // alert((data));
            insertImage();
        },
        /*showDelete:true,
        deleteCallback: function(data,pd)
        {
            for(var i=0;i<data.length;i++)
            {
                $.post("delete.php",{op:"delete",name:data[i]},
                    function(resp, textStatus, jqXHR)
                    {
                        //Show Message
                        $("#status").append("<div>File Deleted</div>");
                    });
            }
            pd.statusbar.hide(); //You choice to hide/not.

        }*/
    }
    var uploadObj = $("#mulitplefileuploader").uploadFile(settings);



    //page layout
    // create page layout
    var pageLayout;

    pageLayout = $('body').layout({
        north: {
            size:					"auto"
            ,	spacing_open:			0
            ,	closable:				false
            ,	resizable:				false
        }
        ,	west: {
            size:					250
            , minSize: 100
            , maxSize: 400
            ,	spacing_closed:			22
            ,	togglerLength_closed:	140
            ,	togglerAlign_closed:	"top"
            ,	togglerContent_closed:	"S<BR>H<BR>O<BR>W"
            ,	togglerTip_closed:		"Open & Pin Contents"
            ,	sliderTip:				"Slide Open Contents"
            ,	slideTrigger_open:		"click"
        }
        ,	east: {
            size:					250
            , minSize: 100
            , maxSize: 400
            ,	spacing_closed:			22
            ,	togglerLength_closed:	140
            ,	togglerAlign_closed:	"top"
            ,	togglerContent_closed:	"S<BR>H<BR>O<BR>W"
            ,	togglerTip_closed:		"Open & Pin Contents"
            ,	sliderTip:				"Slide Open Contents"
            ,	slideTrigger_open:		"click"
        }
    });

    // goto bookmark after creating the layout
   // scrollToBookmark( self.location.hash );

    $(".hasSub").on( "click", function(e) {
        e.preventDefault();
        var $Btn = $(this)
            ,	$List = $Btn.siblings("UL");
        if ($List.is(":visible")) {
            $List
                .css("width", $List.innerWidth())
                .slideUp('fast', function() {$(this).css("width","auto");})
            ;
            $Btn.css({ backgroundImage: 'url("images/icon_tree_on.gif")' });
        }
        else {
            $List.find('li').show();
            $List.slideDown('fast');
            $Btn.css({ backgroundImage: 'url("images/icon_tree_off.gif")' });
        }
    });

    //click image large
    $('.zoom').on('click',function(e){
        e.preventDefault();
        var photo_fullsize =  $(this).attr('src');
        $('#preview-image').html('<a class="fancybox" rel="group" href="'+ photo_fullsize +'"><img src="'+ photo_fullsize +'" alt="" class="img-responsive popup-zoom"></a>');
        $(".fancybox").fancybox();
    });

    //quick filter
    $("#filter").keyup(function(){

        // Retrieve the input field text and reset the count to zero
        var filter = $(this).val(), count = 0;

        // Loop through the comment list
        $("#TOC li").each(function(){
            $(this).find('ul').show();
            // If the list item does not contain the text phrase fade it out
            if ($(this).text().search(new RegExp(filter, "i")) < 0) {
                $(this).fadeOut();

                // Show the list item if the phrase matches and increase the count by 1
            } else {
                $(this).show();
            }

        });

    });



    //right click left menu
    $('#TOC').contextMenu({
        selector: 'li',
        callback: function(key, options) {
            var m = "clicked: " + key + " on " + $(this).text();
            //window.console && console.log(m) || alert(m);
            //console.log(m);
            if(key == 'additem'){
                var id = $(this).data('itemid');
                $("#input-add-itemId").val(id);
                $('#modalAddItem').modal('show');

            }
            if(key == 'addfolder'){
                var id = $(this).data('itemid');
                $("#input-add-folderId").val(id);
                $('#modalAddSubFolder').modal('show');

            }
            else if(key == 'edit'){
                var text = $(this).data('text');
                var id = $(this).data('itemid');
                $("#input-edit-item").val(text);
                $("#input-edit-itemId").val(id);
                $('#modalEditItem').modal('show')
            }
            else if(key == 'delete'){
                var r = confirm("Are you sure?");
                if (r == true) {
                    $(this).fadeOut();
                }
            }
            else if(key == 'copy'){
                var text =  $(this).html();
                $("#copy-to").html(text);
                $("#pasteDisable").val(true);
            }
            else if(key == 'paste'){
                var data =  $("#copy-to").html();
                if( $(this).find("ul").length )
                {
                    $(this).find("ul").append(data);
                }
                else{
                    $(this).append(data);
                }
                $("#pasteDisable").val(1);
            }
            else if(key == 'move'){
                var text =  $(this).html();
                $(this).fadeOut();
                $("#move-to").html(text);
                $("#pasteDisable").val(1);
            }
            else if(key == 'moveto'){
                var data =  $("#move-to").html();
                if( $(this).find("ul").first().length )
                {
                    $(this).find("ul").append(data);
                }
                else{
                    $(this).append(data);
                }
                $(this).find("ul").first().slideDown();
                $("#pasteDisable").val(1);
            }
        },
        items: {
            "addfolder": {name: "New folder", icon: "add"},
            "additem": {name: "New item", icon: "add"},
            "edit": {name: "Rename", icon: "edit"},
            "copy": {
                name: "Copy",
                icon: "copy",
                callback: function() {
                    $("#pasteDisable").val(0);
                }
            },
            "paste": {
                name: "Paste",
                icon: "paste",
                disabled: function(key, opt) {
                    // this references the trigger element
                    var val = $("#pasteDisable").val();
                    if(val == 1){
                        return true
                    }
                    else{
                        return false
                    }
                    //return $("#pasteDisable").val();
                }
            },
            "delete": {name: "Delete", icon: "delete"},
            "move": {
                name: "Move",
                icon: "cut",
                callback: function() {
                    $("#moveDisable").val(0);
                }
            },
            "moveto": {
                name: "Move to",
                icon: "paste",
                disabled: function(key, opt) {
                    // this references the trigger element
                    var val = $("#moveDisable").val();
                    if(val == 1){
                        return true
                    }
                    else{
                        return false
                    }
                    //return $("#pasteDisable").val();
                }
            }
        }
    });
    //get color
    $(".get-color").on("click", function(){
        var color = $(this).data("color");
        $(".get-color").find('i').remove();
        $(this).html('<i class="glyphicon glyphicon-ok"></i>');
        $("#color-add-item").val(color);
    });

    //add  item
    $("#btn-save-folder").click(function(e){
        e.preventDefault();
        var text = $("#input-add-item").val();
        var color = $("#color-add-item").val();
        $("#TOC").append('<li data-text="'+ text +'" data-itemId="5" id="item-5"><a><i class="glyphicon glyphicon-folder-open" style="color:#'+ color +'"></i><span class="item-text">'+text+'</span></a></li>');
        $('#modalAddFolder').modal('hide');
    });
    //add sub folder
    $("#btn-save-subfolder").click(function(e){
        e.preventDefault();
        var text = $("#input-add-subfolder").val();
        var id = $("#input-add-folderId").val();
        var color = $("#color-add-item").val();
        if( $("#item-"+id).find("ul").length )
        {
            // it exists
            $("#item-"+id +">ul").slideDown();
            $("#item-"+id).find("ul").append('<li><a><i class="glyphicon glyphicon-folder-open" style="color:#'+ color +'"></i><span class="item-text">'+text+'</span></a></li>');
        }
        else{
            $("#item-"+id).append('<ul><li><a><i class="glyphicon glyphicon-folder-open"></i><span class="item-text">'+text+'</span></a></li></ul>');
            $("#item-"+id +">ul").slideDown();
            $("#item-"+id +">a").addClass('hasSub');
        }
        $('#modalAddSubFolder').modal('hide');
        sortFunction();
    });
    //add sub item
    $("#btn-save-item").click(function(e){
        e.preventDefault();
        var text = $("#input-add-subitem").val();
        var id = $("#input-add-itemId").val();
        var color = $("#color-add-item").val();
        if( $("#item-"+id).find("ul").length )
        {
            // it exists
            $("#item-"+id +">ul").slideDown();
            $("#item-"+id).find("ul").append('<li><a><i class="glyphicon glyphicon-file" style="color:#'+ color +'"></i><span class="item-text">'+text+'</span></a></li>');
        }
        else{

            $("#item-"+id).append('<ul><li><a><i class="glyphicon glyphicon-file"></i><span class="item-text">'+text+'</span></a></li></ul>');
            $("#item-"+id +">ul").slideDown();
            $("#item-"+id +">a").addClass('hasSub');
        }
        $('#modalAddItem').modal('hide');
    });
    //save edit item
    $("#btn-save-edit-item").click(function(e){
        e.preventDefault();
        var text = $("#input-edit-item").val();
        var id = $("#input-edit-itemId").val();
        $("#item-"+id).find('.item-text').html(text);
        $('#modalEditItem').modal('hide');
    });


});


